

//
//  ListTableViewController.swift
//  Contact
//
//  Created by YYY on 2017/7/20.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class ListTableViewController: UITableViewController {

    var listArray = [Person]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册cell
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "identify")
        //只是闭包对self进行了copy，闭包执行完成后，会自动销毁，同时释放对self的引用
        requestData { (list) in
            //闭包中定义好的代码在需要的时候执行，需要self指定语境
            self.listArray += list

            //刷新表格
            self.tableView.reloadData()
        }
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    @IBAction func addPerson(_ sender: Any)
    {
        //添加联系人
        performSegue(withIdentifier: "list2detail", sender: nil)
    }

    
    func requestData(completion: @escaping ([Person]) ->())
    {
        //异步请求数据
        DispatchQueue.global().async {
            print("数据正在加载中....")
            //停留1s
            Thread.sleep(forTimeInterval: 1)
            var dataArray = [Person]()
            
            for i in 0..<20
            {
                let p = Person()
                p.name = "zhang \(i)"
                p.phone = "15210" + String(format: "%06d", arc4random_uniform(1000000))
                p.title = "Boss"
                dataArray.append(p)
            }
            
            DispatchQueue.main.async(execute: { 
                completion(dataArray)
            })
           
        }
    }
    

    
    // MARK: - Table view data source

    // MARK: 数据源方法
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listArray.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "identify", for: indexPath)
        
        
        if listArray.count>0
        {
            let person = listArray[indexPath.row]
            cell.textLabel?.text = person.name
            cell.textLabel?.textColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
            
            cell.detailTextLabel?.textColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
            cell.detailTextLabel?.text = person.phone
        }
        
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        performSegue(withIdentifier: "list2detail", sender: indexPath)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        let vc = segue.destination as! DetailTableViewController

        //if let 和 guard let判空的，一律使用as？
        //as? 或者 as!直接根据前面的返回值来决定
        //swift中，除了String外，绝大多数使用as需要！或者？
        if let indexPath = sender as? IndexPath
        {
            vc.person = listArray[indexPath.row]
            
            vc.completion = {
                //刷新指定行
                self.tableView.reloadRows(at: [indexPath], with: .automatic)
            }
        }
        else
        {
            //循环引用 vc引用了闭包
            vc.completion = { [weak vc] in
                //闭包引用了vc
                guard let p = vc?.person else {
                    return
                }
                self.listArray.insert(p, at: 0)
                self.tableView.reloadData()
//                let p = vc.person
//
                
            }
        }
        
    }
    
    
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
